<template>
  <n-card title="卡片">
    <div class="flex flex-wrap">
      <n-button text @click="parentId = '-1'"> 全部 </n-button>
      <n-button
        text
        v-for="item in treeData"
        :key="item.id"
        @click="parentId = item.id"
        class="mr-2"
      >
        {{ item.name }}
      </n-button>
    </div>
  </n-card>
  <!-- 下方为每个exam的列表 -->
  <div class="container">
    <div
      class="exam flex h-[200px] w-full mb-2 bg-white"
      v-for="item in examShowList"
      :key="item.id"
      @click="handleToExamDetail(item.id)"
    >
      <div class="pic h-full w-[100px]">
        <n-image
          :src="buildPicUrl(item.pic || 'xxx')"
          fallback-src="../../../assets/images/R-C.png"
        ></n-image>
      </div>
      <div class="text-[20px]">{{ item.name }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getExamByPage } from '@/api/exam'
import type { ExamRes } from '@/types/exam'
import { arrayToTree } from '@/utils'
import { buildPicUrl } from '@/utils/commonBusiness'
const examList = ref<ExamRes[]>([])
const treeData = ref<any[]>([])
const router = useRouter()
onMounted(() => {
  loadAllExams()
})

const parentId = ref('-1')

const examShowList = computed(() => {
  if (parentId.value === '-1') {
    return examList.value.filter((item) => item.pid !== '-1')
  }

  return examList.value.filter((item) => item.pid === parentId.value)
})

const handleToExamDetail = (id: string) => {
  router.push({
    name: 'examDetail',
    query: {
      examId: id
    }
  })
}

const loadAllExams = () => {
  getExamByPage({
    page: 1,
    pageSize: 9999
  }).then((res) => {
    examList.value = res.data.items
    // 转换为树形结构
    treeData.value = arrayToTree(examList.value, 'pid', '-1')
  })
}
</script>

<style scoped lang="scss"></style>
